import os
from core.tool_registry import register_tool


@register_tool(
    tool_id="file_reader",
    name="本地文件读取工具",
    description="读取文本文件内容，输入格式: 读文件 [文件路径]",
    parameters=[
        {
            "name": "file_path",
            "type": "string",
            "required": True,
            "desc": "文本文件的绝对路径"
        }
    ]
)
def read_file(file_path: str) -> str:
    """读取本地文本文件内容"""
    if not os.path.exists(file_path):
        return f"文件不存在: {file_path}"
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read(500)  # 限制显示长度
    return f"路径: {file_path}\n内容: {content}..."


@register_tool(
    tool_id="csv_counter",
    name="CSV行数统计工具",
    description="统计CSV文件行数，输入格式: 统计行数 [文件路径]",
    parameters=[
        {
            "name": "file_path",
            "type": "string",
            "required": True,
            "desc": "CSV文件的绝对路径"
        }
    ]
)
def count_csv_lines(file_path: str) -> str:
    """统计CSV文件行数（依赖pandas）"""
    import pandas as pd
    if not os.path.exists(file_path):
        return f"文件不存在: {file_path}"
    df = pd.read_csv(file_path)
    return f"路径: {file_path}\n行数: {len(df)}\n列名: {list(df.columns)}"


@register_tool(
    tool_id="calculator",
    name="数学计算器",
    description="执行数学运算，输入格式: 计算 [表达式]",
    parameters=[
        {
            "name": "expression",
            "type": "string",
            "required": True,
            "desc": "数学表达式（支持+、-、*、/、()）"
        }
    ]
)
def calculate(expression: str) -> str:
    """执行简单数学计算"""
    try:
        # 注意：实际应用需用安全的表达式解析库（如ast）
        result = eval(expression, {"__builtins__": None})
        return f"表达式: {expression}\n结果: {result}"
    except Exception as e:
        return f"计算失败: {str(e)}"


@register_tool(
    tool_id="file_writer",
    name="文件生成工具",
    description="生成文本文件，输入格式: 生成文件 [路径] [内容]",
    parameters=[
        {
            "name": "file_path",
            "type": "string",
            "required": True,
            "desc": "要生成的文件路径"
        },
        {
            "name": "content",
            "type": "string",
            "required": True,
            "desc": "文件内容"
        }
    ]
)
def write_file(file_path: str, content: str) -> str:
    """生成并写入文本文件"""
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(content)
        return f"文件已生成: {file_path}\n内容: {content}"
    except Exception as e:
        return f"生成失败: {str(e)}"